/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Terry
 */
public class IO {
    
    private static String fileName = "clients.xml";
    
    
    // read xml file to check username
    
    public static boolean checkUsername(String username)
    {
      
        try{
        NodeList nodes = getClientNode(username);
        

            if(nodes.getLength() >= 1)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        catch(Exception ex)
        {
            
            return false;
        }
       
    }
    
    
    
    
    public static NodeList getClientNode(String username) throws Exception
    {
        
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = parser.parse(new java.io.File((fileName )));
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("//client[username = '" +username + "']", doc, XPathConstants.NODESET);
        
        return nodes;
        
    }
    
    public static NodeList getClientNode(String username, String password) throws Exception
    {
        
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = parser.parse(new java.io.File((fileName)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("//client[username = '" +username + "' and password = '" +password + "']", doc, XPathConstants.NODESET);
	
        
        return nodes;
        
    }
    
    
    
    public static boolean checkPassword(String username, String password) throws Exception
    {
    
        NodeList nodes = getClientNode(username,password);
      	    
        if(nodes.getLength() >= 1)
        {
            return true;
        }
        else
        {
            return false;
        }
        
        
    }
    
    
   public static boolean userInputInteger(String integer)
    {
  
        try 
        {
           
            Integer.parseInt(integer.trim());
            return true;
            
        }
        catch(Exception ex)
        {
            return false; 
        }
    
    }
            
      
    
}
